package com.exp3.virus.service;

import com.exp3.virus.model.RegionStates;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.http.Header;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;



import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class CsvDataService implements InitializingBean{

    private final String CORONA_VIRUS_URL=
            "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private final ArrayList<RegionStates> allRegionStates = new ArrayList<RegionStates>();
    public List<RegionStates> getAllRegionStates() { return  allRegionStates; }

    @Scheduled(cron = " 0 0 1 * * *")  //数据每天获取一次，周期设置成一天
    public void fetchCoronaVirusData() throws IOException {
        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_URL))  //headers 和 header 是不同的！！报错时，要留心是不是哪里名字打错了
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        //Resource要导入对，很多同名的，问题出错时，也要检查是不是import 的 class 不对
        ResponseEntity<org.springframework.core.io.Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        InputStream is=body.getInputStream();  //这里是读取CSV文件的关键步骤
        Reader reader= new InputStreamReader(is);
        Iterable<CSVRecord> parser = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
        for(CSVRecord record : parser){
            RegionStates regionStates = new RegionStates();
            int today = Integer.parseInt(record.get(record.size()-1));
            int yesterday = Integer.parseInt(record.get(record.size()-2));
            regionStates.setState(record.get("Province/State"));
            regionStates.setCountry(record.get("Country/Region"));
            regionStates.setLatestTotalCases(today);
            regionStates.setDiffFromPrevDay(today-yesterday); //单项记录的设置
            allRegionStates.add(regionStates);  //一项记录加入所有记录列表对象中
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
